package tk.djcrazy.instantmessage.eventhandler;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import tk.djcrazy.instantmessage.domain.LoginState;
import tk.djcrazy.instantmessage.domain.UserState;

public final class UserLoginStateHandler {
	private final static Map<Integer, UserState> USER_LOGIN_STATE = new ConcurrentHashMap<Integer, UserState>();
	
	public void changeUserLoginState(int userId, LoginState state) {
		if (USER_LOGIN_STATE.containsKey(userId)) {
			UserState userState = USER_LOGIN_STATE.get(userId);
			userState.setState(state);
			userState.setLastActiveTime(new Date());
		} else {
			UserState userState = new UserState();
			userState.setUserId(userId);
			userState.setLastActiveTime(new Date());
			userState.setState(state);
			USER_LOGIN_STATE.put(userId, userState);
		}
	}
	public LoginState getState(int userId) {
		if (USER_LOGIN_STATE.containsKey(userId)) {
			LoginState state = USER_LOGIN_STATE.get(userId).getState();
			Date last = USER_LOGIN_STATE.get(userId).getLastActiveTime();
			if (state!=LoginState.OFF_LINE) {
				if ((new Date()).getTime()-last.getTime()>30000) {
					return LoginState.OFF_LINE;
				} else {
					return LoginState.ON_LINE;
				}
			} else {
				return LoginState.OFF_LINE;
			}
		}
		else {
			return LoginState.OFF_LINE;
		}
	}
	
	public void updateOnlineState(int id) {
		if (USER_LOGIN_STATE.containsKey(id)&& USER_LOGIN_STATE.get(id).getState()!=LoginState.OFF_LINE) {
			UserState userState = USER_LOGIN_STATE.get(id);
			userState.setLastActiveTime(new Date());
		} else if (USER_LOGIN_STATE.containsKey(id)) {
			UserState userState = USER_LOGIN_STATE.get(id);
			userState.setLastActiveTime(new Date());
			userState.setState(LoginState.ON_LINE);
		} else {
			UserState state = new UserState();
			state.setUserId(id);
			state.setState(LoginState.ON_LINE);
			state.setLastActiveTime(new Date());
		}
	}
}
